package com.lyz.remote.impl;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import com.lyz.log.filter.IFilter;

public abstract class AbstractHttpSender implements Runnable {
	
	private static final Logger logger = Logger.getLogger(AbstractHttpSender.class);
	/*以2开头表示请求成功*/
	private final int SUCCESSRESPONSE = 2;
	
	private String url = null;
	
	private IFilter filter = null;
	
	private DefaultHttpClient httpClient = null;
	
	private String msg = null;
	/*是否需要验证服务器端的返回值*/
	private boolean isNeedReturn = false;
	
	public AbstractHttpSender(IFilter filter, boolean isNeedReturn){
		this.filter = filter;
		this.isNeedReturn = isNeedReturn;
	}
	/**
	 * 需要在线程启动之前被调用，即run方法运行之前
	 * @param client
	 * @param url
	 * @param msg
	 */
	public void init(DefaultHttpClient client, String url, String msg){
		
		this.httpClient = client;
		this.url = url;
		this.msg = msg;
	}

	@Override
	public void run() {
		
		try {
			doSendMsg0(this.msg);
		} catch (Exception e) {
			logger.warn("fail to send message!",e);
		}
		
	}
	
	/**
	 * 
	 * @param msg
	 * @return 0-发送成功；1-文本过滤、解析错误；2-http发送失败(需要重新发送的)；
	 */
	public int doSendMsg0(String msg) {
		
		if(msg == null || "".equals(msg.trim())){
			return 1;
		}
		
		/*过滤数据*/
		msg = filter.filter(msg);

		if(msg == null){
			return 1;
		}
		
//		msg = URLEncoder.encode(msg);
		
		/*拼接uri*/
		String req = url+"?"+msg;
		HttpGet get = new HttpGet(req);
		HttpResponse response = null;
        InputStream is = null;
        
		/*执行get请求*/
		try {
			response = httpClient.execute(get);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				is = entity.getContent();
			}		
		} catch (ClientProtocolException e) {
			logger.error("protocol error", e);
			if(get != null){
				get.releaseConnection();
				get = null;
			}
			return 3;
		} catch (IOException e) {
			logger.error("fail to send data!",e);
			if(get != null){
				get.releaseConnection();
				get = null;
			}
			return 2;
		}
		
        /*判断状态码是否是成功响应*/
        if((response.getStatusLine().getStatusCode()/100) != SUCCESSRESPONSE){
        	logger.error("fail to response! http status code:"+response.getStatusLine().getStatusCode());
        	if(get != null){
				get.releaseConnection();
				get = null;
			}
        	
        	return 3;
        }
        /*获取返回值*/
        String line = null;
        if(isNeedReturn){
        	line = getReturn(is, get);
        	if(line == null){
        		return 4;
        	}    	
        }
             
        /*尽快释放资源*/
      if(get != null){
			get.releaseConnection();
			get = null;
      }
      
      /*判断返回值是否合法*/
      if(isNeedReturn && (!isValidRespCode(line))){
      	logger.warn("error response value:"+line);
      	return 5;
      }
      
      logger.debug("sender:"+req);
      
      return 0;
	}
	
	private String getReturn(InputStream is, HttpGet get){
		/*返回值判断*/
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = null;
        try {
			do{
				line = reader.readLine();
				if(line != null && !"".equals(line.trim())){
					buffer.append(line);
				}
			}while(line != null);
		} catch (IOException e) {
			logger.error("exception when read data from network inputstream!",e);
			if(get != null){
				get.releaseConnection();
				get = null;
			}
			try {
				if(reader != null){
					reader.close();
					reader = null;
				}
			} catch (IOException e1) {
				logger.warn(e1);
			}
			return null;
		}
        
        return buffer.toString();
	}
	/**
	 * 判断返回值是否正确
	 * @param resp
	 * @return
	 */
	public abstract boolean isValidRespCode(String resp);

}
